//
//  CSendToolView.m
//  Learn
//
//  Created by Mac on 16/9/29.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "CSendToolView.h"
#define _UIKeyboardFrameEndUserInfoKey (&UIKeyboardFrameEndUserInfoKey != NULL ? UIKeyboardFrameEndUserInfoKey : @"UIKeyboardBoundsUserInfoKey")
@interface CSTSpaceLable : UITextView

@end

@implementation CSTSpaceLable
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    return false;
}
@end

@interface CSendToolView()<UITextViewDelegate>
@property (nonatomic, strong) UITextView *textView; // 输入框
@property (nonatomic, strong) CSTSpaceLable *lblSpace; // 占位符
@property (nonatomic, strong) UIView *btnview;
@property (nonatomic, strong) UILabel *btnSend;
@property (nonatomic, strong)UIImageView *imgView;
@property (nonatomic, strong)UIView *circleView;
@end

@implementation CSendToolView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initView];
    }
    return self;
}
- (void)setIsImage:(BOOL)isImage
{
    if (isImage==YES) {

        self.circleView.backgroundColor=C(@"f7d30a");

    }else
    {
        self.circleView.backgroundColor=[UIColor clearColor];
    }
}
- (void) initView{
    [self setBackgroundColor:[UIColor whiteColor]];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, .5)];
    [self addSubview:lineView];
 
    [lineView setBackgroundColor:C(@"eaeaea")];
    UIImage *imgBtn = [UIImage imageNamed:@"Ico_discuss_default"];
    UIView *btnview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, MAX(imgBtn.size.width + 30, 50), CGRectGetHeight(self.frame))];
    [self addSubview:btnview];
    
    _btnview = btnview;
    [btnview setUserInteractionEnabled:YES];
    UITapGestureRecognizer *tapClick = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(btnTapAction:)];
    [btnview addGestureRecognizer:tapClick];
  
    
    self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake((btnview.bounds.size.width-imgBtn.size.width)/2, (btnview.bounds.size.height-imgBtn.size.height)/2, imgBtn.size.width, imgBtn.size.height)];//WithImage:imgBtn];
    [btnview addSubview: self.imgView];
//    [ self.imgView setCenter:btnview.center];
    [ self.imgView setImage:imgBtn];
    
    self.circleView=[[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.imgView.frame)-3,(btnview.bounds.size.height-imgBtn.size.height)/2-3, 6, 6)];
    self.circleView.layer.masksToBounds=YES;
    self.circleView.layer.cornerRadius=3.0;
    [btnview addSubview:self.circleView];
    
    float windowwidth = CGRectGetWidth([UIScreen mainScreen].bounds);
    UILabel *btnSend = [[UILabel alloc] initWithFrame:CGRectMake(windowwidth - 15 - 50, 5, 50, CGRectGetHeight(self.frame) - 10)];
    [self addSubview:btnSend];
    _btnSend = btnSend;
    [btnSend setText:@"发送"];

    btnSend.backgroundColor = MainColor;
    btnSend.textColor = [UIColor whiteColor];
    btnSend.font = F(10);
    [btnSend setTextAlignment:NSTextAlignmentCenter];
    [btnSend setUserInteractionEnabled:YES];
    UITapGestureRecognizer *tapClickSend = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(btnSendAction:)];
    [btnSend addGestureRecognizer:tapClickSend];
    
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(btnview.frame) + 10, 5, windowwidth - 10 - CGRectGetWidth(btnview.frame) - CGRectGetWidth(btnSend.frame) - 10- 10, CGRectGetHeight(self.frame) - 10)];
    [self addSubview:_textView];
    _textView.delegate=self;
    _textView.backgroundColor = C(@"e3e3e3");
    [_textView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    
    _lblSpace = [[CSTSpaceLable alloc] initWithFrame:_textView.frame];
    [_lblSpace setBackgroundColor:[UIColor clearColor]];
    [_lblSpace setTextColor:[UIColor grayColor]];
    [_lblSpace setText:@"回复："];
    [self addSubview:_lblSpace];
}

- (void)setReplyName:(NSString *)replyName{
    if (replyName && replyName.length > 0) {
        self.textView.text = [NSString stringWithFormat:@"回复 %@：", replyName];
        [_lblSpace setHidden:YES];
    }else{
        self.textView.text = @"";
        [_lblSpace setHidden:NO];
    }
    
}

- (void)setReplyInfo:(NSDictionary *)replyInfo{
    _replyInfo = replyInfo;
    NSString *replyName = replyInfo[@"name"];
    if (replyName && replyName.length > 0) {
        self.textView.text = [NSString stringWithFormat:@"回复 %@：", replyName];
        [_lblSpace setHidden:YES];
    }else{
        self.textView.text = @"";
        [_lblSpace setHidden:NO];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    CGRect frame = _textView.frame;
    if (_textView.contentSize.height > 80) {
        return;
    }
    frame.size.height = MAX(30, _textView.contentSize.height);
    [_textView setFrame:frame];
    [_lblSpace setFrame:frame];
    
    CGRect selfframe = self.frame;
    float diff = frame.size.height + 10 - self.frame.size.height;
    selfframe.origin.y -= diff;
    selfframe.size.height += diff;
    self.frame = selfframe;
    
    CGRect btnframe = _btnview.frame;
    btnframe.origin.y += diff;
    _btnview.frame = btnframe;
    
    CGRect sendframe = _btnSend.frame;
    sendframe.origin.y += diff;
    _btnSend.frame = sendframe;
    
    if (self.changeFrame) {
        self.changeFrame(self.frame);
    }
    if(frame.size.height > 30) return;
    CGFloat topCorrect = ([_textView bounds].size.height - [_textView contentSize].height);
    topCorrect = (topCorrect <0.0 ?0.0 : topCorrect);
    _textView.contentOffset = (CGPoint){.x =0, .y = topCorrect/2};
    _lblSpace.contentOffset = _textView.contentOffset;
}

- (void) btnTapAction:(UIGestureRecognizer *)gesture{
    if (self.btnAction) {
        self.btnAction();
    }
    [_textView resignFirstResponder];
}

- (void) btnSendAction:(UIGestureRecognizer *)gesture{
    if (self.sendAction) {
       
        self.sendAction(_textView.text);

//      _textView.text=@"";
        
    }
    [_textView resignFirstResponder];
}

- (void)viewWillAppear{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ShowKeyboard:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TextChange:) name:UITextViewTextDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TextEndEdit:) name:UITextViewTextDidEndEditingNotification object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeKey:) name:@"closeKeyboard" object:nil];
}

- (void)viewWillDisAppear{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void) ShowKeyboard:(NSNotification*)notification{
    CGRect keyboardRect = [self convertRect:[[[notification userInfo] objectForKey:_UIKeyboardFrameEndUserInfoKey] CGRectValue] fromView:nil];
    if (CGRectIsEmpty(keyboardRect)) {
        return;
    }
    CGRect frame = self.frame;
    frame.origin.y = CGRectGetMinY(self.frame) + CGRectGetMinY(keyboardRect) - CGRectGetHeight(frame);
    if (keyboardRect.origin.y < CGRectGetMaxY(self.frame)) {
        [UIView animateWithDuration:[[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
            self.frame = frame;
        } completion:^(BOOL finished) {
            if (self.changeFrame) {
                self.changeFrame(frame);
            }
        }];
    }
}

- (void) HideKeyboard:(NSNotification*)notification{
    CGRect keyboardRect = [self convertRect:[[[notification userInfo] objectForKey:_UIKeyboardFrameEndUserInfoKey] CGRectValue] fromView:nil];
    if (CGRectIsEmpty(keyboardRect)) {
        return;
    }
    
    CGRect frame = self.frame;
    frame.origin.y = CGRectGetMinY(self.frame) + CGRectGetMinY(keyboardRect) - CGRectGetHeight(frame);
    
    [UIView animateWithDuration:[[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        self.frame = frame;
    } completion:^(BOOL finished) {
        
    }];
    if (self.changeFrame) {
        self.changeFrame(frame);
    }
}

- (void) TextChange:(NSNotification *) notification{
    if (self.textView.text.length > 0) {
        [_lblSpace setHidden:YES];
    }else if(self.textView.text.length == 0){
        [_lblSpace setHidden:NO];
    }
}
- (void)closeKey:(NSNotification *) notificati
{
    [self.textView resignFirstResponder];

}
- (void) TextEndEdit:(NSNotification *) notification{
    if ([self.textView.text isEqualToString:self.lblSpace.text] || [self.textView.text isEqualToString:@""]) {
        self.textView.text = @"";
        [_lblSpace setHidden:NO];
    }
}

- (BOOL)isFirstResponder{
    return self.textView.isFirstResponder;
}

- (BOOL)resignFirstResponder{
    return [self.textView resignFirstResponder];
}

- (BOOL)becomeFirstResponder{
    return [self.textView becomeFirstResponder];
}

- (void)textViewDidChange:(UITextView *)textView{
    
    if (textView.markedTextRange == nil && textView.text.length > 200)  //加上 textView.markedTextRange == nil判断，当此属性为nil时，代表不在这种联想输入等待确定状态。
        
    {
        
        textView.text = [textView.text substringToIndex:200];
        
    }
}


@end
